#include "stdafx.h"
#include "Visualizer.h"

using namespace Gdiplus;

Library::Visualizer::Visualizer(HDC hdc, const std::vector<std::pair<double, double> >& points, const int displayHeight, const int displayWeigth)
    : hdc_(hdc), points_(points), displayHeight_(displayHeight), displayWeight_(displayWeigth), graphics_(hdc), pen_(Gdiplus::Color(128, 0, 0, 255))
{
    MapCoordinatesToScreen();
}

void Library::Visualizer::Draw(const std::vector<std::pair<int, int> >& connections)
{
    for (size_t i = 0; i < connections.size(); ++i)
    {
        int p1x = (int)points_[connections[i].first].first;
        int p1y = (int)points_[connections[i].first].second;
        int p2x = (int)points_[connections[i].second].first;
        int p2y = (int)points_[connections[i].second].second;

        LineTo(hdc_/*&pen_*/, /*p1x, p1y, */p1x, p1y);
        LineTo(hdc_/*&pen_*/, /*p1x, p1y, */p2x, p2y);
    }
}

double Library::Visualizer::GetMaxHeight()
{
    double result = max(points_[0].second, points_[1].second);
   
    for (size_t i = 2; i < points_.size(); ++i)
    {
        result = max(result, points_[i].second);
    }

    return result;
}

double Library::Visualizer::GetMaxWidth()
{
    double result = max(points_[0].first, points_[1].first);
   
    for (size_t i = 2; i < points_.size(); ++i)
    {
        result = max(result, points_[i].first);
    }

    return result;
}

double Library::Visualizer::GetMinHeight()
{
    double result = min(points_[0].second, points_[1].second);
   
    for (size_t i = 2; i < points_.size(); ++i)
    {
        result = min(result, points_[i].second);
    }

    return result;
}

double Library::Visualizer::GetMinWidth()
{
    double result = min(points_[0].first, points_[1].first);
   
    for (size_t i = 2; i < points_.size(); ++i)
    {
        result = min(result, points_[i].first);
    }

    return result;
}

void Library::Visualizer::MapCoordinatesToScreen()
{
    double minHeight = GetMinHeight();
    double minWeight = GetMinWidth();
    double maxHeight = GetMaxHeight();
    double maxWeight = GetMaxWidth();
    double dx = 0;
    double dy = 0;

    if (minWeight < 0)
    {
        dx = minWeight;
    }

    if (minHeight < 0)
    {
        dy = minHeight;
    }

    for (size_t i = 0; i < points_.size(); ++i)
    {
        points_[i].first  -= dx;
        points_[i].second -= dy;
    }

    double xScale = (maxWeight - minWeight) / (1.0 * displayWeight_);
    double yScale = (maxHeight - minHeight) / (1.0 * displayHeight_);

    for (size_t i = 0; i < points_.size(); ++i)
    {
        points_[i].first  /= xScale;
        points_[i].second /= yScale;
    }
}
